package com.xiaojie.persistence.core.builder;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.xiaojie.persistence.core.ExecutorTypeEnum;
import com.xiaojie.persistence.core.entity.BoundSql;
import com.xiaojie.persistence.core.entity.Configuration;
import com.xiaojie.persistence.core.entity.MappedStatement;
import com.xiaojie.persistence.core.entity.ParameterMapping;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Nick
 * @date 2021/5/5
 * @description Mapper解析器构造器
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    private Map<String, ExecutorTypeEnum> executorTypeMap = new HashMap<>();

    public XMLMapperBuilder() {
        for (ExecutorTypeEnum executorTypeEnum : ExecutorTypeEnum.values()) {
            executorTypeMap.put(executorTypeEnum.getKeyName(), executorTypeEnum);
        }
    }

    public XMLMapperBuilder(Configuration configuration) {
        this();
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {

        Document document = new SAXReader().read(inputStream);

        // 根节点 <mapper>
        Element rootElement = document.getRootElement();
        // 解析 元素
        parseCRUD(rootElement);
    }


    private void parseCRUD(Element rootElement) throws ClassNotFoundException {

        // 用来组装 statementId
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selects = rootElement.selectNodes("//select|//update|//insert|//delete");

        for (Element element : selects) {

            ExecutorTypeEnum executorType = executorTypeMap.get(element.getName());
            if (executorType == null) {
                continue;
            }

            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String statementId = namespace + "." + id;
            String sqlText = element.getTextTrim();
            Class parameterTypeClass = parameterType == null ? null : Class.forName(parameterType);
            Class resultTypeClass = resultType == null ? null : Class.forName(resultType);
            BoundSql boundSql = parseBoundSql(sqlText);
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(statementId);
            mappedStatement.setSql(sqlText);
            mappedStatement.setParameterType(parameterTypeClass);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setBoundSql(boundSql);
            mappedStatement.setExecutorType(executorType);
            configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }
    }

    private BoundSql parseBoundSql(String sqlText) {

        // 使用正则,将所有的动态参数解析出来,并设置好原始sql #{xxx}
        // 用于替换?的正则表达式
        String replaceReg = "\\#\\{(.+?)\\}";
        // 用于提取参数的正则表达式
        String getParamReg = "(?<=\\{)(.+?)(?=\\})";
        Pattern pattern = Pattern.compile(getParamReg);
        Matcher matcher = pattern.matcher(sqlText);
        List<String> params = new ArrayList<>();
        List<ParameterMapping> parameterMappingList = new ArrayList<>();
        int index = 0;
        while (matcher.find()) {
            index++;
            String parameterName = matcher.group(1);
            ParameterMapping parameterMapping = new ParameterMapping();
            parameterMapping.setIndex(index);
            parameterMapping.setParameterName(parameterName);
            params.add(parameterName);
            parameterMappingList.add(parameterMapping);

        }

        // 转换用于预编译的SQL
        String preSql = sqlText.replaceAll(replaceReg, "?");

        BoundSql boundSql = new BoundSql();
        boundSql.setSqlText(preSql);
        boundSql.setParameterMappingList(parameterMappingList);
        return boundSql;
    }


}
